import { defineStore } from 'pinia'
import { fetchMenuList } from '@/api/menuApi'
import { ref } from 'vue'
import logger from '@/utils/logger'

export const useMenuStore = defineStore(
  'menu',
  () => {
    const menuList = ref([])
    const activeMenu = ref('')
    const breadcrumbs = ref([])

    // 添加标签页相关状态
    const tabsList = ref([
      { title: '首页', name: 'home', path: '/home', closable: false }, // 首页标签不可关闭
    ])
    const activeTab = ref('home')

    /**
     * @description 获取菜单列表
     */
    const fetchMenuData = async () => {
      try {
        const res = await fetchMenuList()
        if (res.code === 200) {
          menuList.value = res.data
          return res.data
        } else {
          logger.warn('获取菜单列表失败', res)
          return []
        }
      } catch (error) {
        logger.error('获取菜单列表失败', error)
        return []
      }
    }

    /**
     * @description 通过menuPath查找菜单项
     * @param {String} menuPath 菜单路径
     * @return {Object|null} 找到的菜单项或null
     */
    const findMenuByPath = (menuPath) => {
      const find = (menus) => {
        for (const menu of menus) {
          if (menu.menuPath === menuPath) {
            return menu
          }

          if (menu.children && menu.children.length) {
            const found = find(menu.children)
            if (found) {
              return found
            }
          }
        }
        return null
      }

      return find(menuList.value)
    }

    /**
     * @description 点击菜单项
     * @param {Object|String} menuOrPath 菜单项对象或menuPath
     * @param {Object} router Vue Router实例
     */
    const handleMenuClick = (menuOrPath, router) => {
      try {
        // 确定菜单项
        let menu = null

        if (typeof menuOrPath === 'string') {
          // 如果传入的是字符串，作为menuPath查找
          menu = findMenuByPath(menuOrPath)
        } else if (typeof menuOrPath === 'object') {
          // 如果传入的是对象，直接使用
          menu = menuOrPath
        }

        // 如果没有找到菜单项，则直接返回
        if (!menu) {
          logger.warn('未找到菜单项', menuOrPath)
          return
        }

        // 更新面包屑
        const breadcrumbsPath = []

        // 找到当前点击的菜单项及其所有父级
        findMenuPathByComponent(menuList.value, menu.menuPath, breadcrumbsPath)

        updateBreadcrumbs(breadcrumbsPath)
        setActiveMenu(menu.menuPath)

        // 如果有menuPath并且是叶子节点，则进行路由导航
        if (menu.menuPath && (menu.leaf || !menu.children || !menu.children.length)) {
          router.push({ name: menu.menuPath })
        }
      } catch (error) {
        logger.error('处理菜单点击失败', error)
      }
    }

    /**
     * @description 递归查找菜单路径 - 使用menuPath作为标识符
     */
    const findMenuPathByComponent = (menus, menuPath, path = []) => {
      for (const menu of menus) {
        if (menu.menuPath === menuPath) {
          path.push({
            id: menu.id,
            title: menu.text,
            path: menu.menuPath ? { name: menu.menuPath } : null,
          })
          return true
        }

        if (menu.children && menu.children.length) {
          const tempPath = {
            id: menu.id,
            title: menu.text,
            path: menu.menuPath ? { name: menu.menuPath } : null,
          }

          if (findMenuPathByComponent(menu.children, menuPath, path)) {
            // 如果在子菜单中找到了目标，则将当前菜单添加到路径的开头
            path.unshift(tempPath)
            return true
          }
        }
      }

      return false
    }

    /**
     * @description 更新面包屑
     */
    const updateBreadcrumbs = (path) => {
      breadcrumbs.value = path
    }

    /**
     * @description 设置当前激活的菜单
     */
    const setActiveMenu = (menuPath) => {
      activeMenu.value = menuPath
    }

    /**
     * @description 通过路由名称查找并激活菜单
     * @param {String} routeName 路由名称
     * @param {Object} router Vue Router实例
     */
    const setActiveMenuByRouteName = (routeName, router) => {
      const menu = findMenuByPath(routeName)
      if (menu) {
        handleMenuClick(menu, router)
        return true
      }
      return false
    }

    /**
     * @description 添加标签页
     * @param {Object} route 路由对象
     */
    const addTab = (route) => {
      try {
        // 检查是否已存在相同路由的tab
        const isExist = tabsList.value.some((tab) => tab.name === route.name)

        if (!isExist && route.name) {
          // 优先使用路由meta中的title，如果没有则查找菜单项获取title
          let title = route.name

          if (route.meta && route.meta.title) {
            title = route.meta.title
          } else {
            // 尝试从菜单数据中获取标题
            const menuItem = findMenuByPath(route.name)
            if (menuItem) {
              title = menuItem.text
            }
          }

          tabsList.value.push({
            title,
            name: route.name, // 使用路由的name作为tab的name
            path: route.path,
            closable: route.name !== 'home', // 只有非首页标签可关闭
          })
        }

        activeTab.value = route.name
      } catch (error) {
        logger.error('添加标签页失败', error)
      }
    }

    /**
     * @description 关闭标签页
     * @param {String} tabName 标签页名称
     * @param {Object} router Vue Router实例
     */
    const removeTab = (tabName, router) => {
      try {
        // 首页标签不允许关闭
        if (tabName === 'home') {
          return
        }

        // 如果关闭的是当前激活的tab，需要激活其他tab
        if (activeTab.value === tabName) {
          tabsList.value.forEach((tab, index) => {
            if (tab.name === tabName) {
              const nextTab = tabsList.value[index + 1] || tabsList.value[index - 1]
              if (nextTab) {
                activeTab.value = nextTab.name
                // 导航到新的标签页
                router.push({ name: nextTab.name })
                setActiveMenu(nextTab.name)
              }
            }
          })
        }

        // 从数组中移除关闭的tab
        tabsList.value = tabsList.value.filter((tab) => tab.name !== tabName)
      } catch (error) {
        logger.error('关闭标签页失败', error)
      }
    }

    /**
     * @description 设置当前激活的标签页
     */
    const setActiveTab = (tabName) => {
      activeTab.value = tabName
    }
    /**
     * @description 用于退出登录清除所有信息
     */
    const clearMenuData = () => {
      menuList.value = []
      activeMenu.value = ''
      breadcrumbs.value = []
      tabsList.value = []
      activeTab.value = 'home'
    }

    return {
      menuList,
      activeMenu,
      breadcrumbs,
      tabsList,
      activeTab,
      fetchMenuData,
      updateBreadcrumbs,
      setActiveMenu,
      handleMenuClick,
      setActiveMenuByRouteName,
      findMenuByPath,
      findMenuPathByComponent,
      addTab,
      removeTab,
      setActiveTab,
      clearMenuData,
    }
  },
  {
    persist: true,
  },
)
